package com.mediacloud.app.newsmodule.fragment.baoliao.frag;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.GsonUtils;
import com.chinamcloud.collect.AcquisitionManager;
import com.mediacloud.app.assembly.util.StringUtils;
import com.mediacloud.app.model.component.ComponentItem;
import com.mediacloud.app.model.fragment.BaseFragment;
import com.mediacloud.app.model.interfaces.DataInvokeCallBack;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.BaoLiaoMeta;
import com.mediacloud.app.model.news.BaseMessageReciver;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.model.utils.DefaultBgUtil;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.activity.microlive.XdNineGridDivider;
import com.mediacloud.app.newsmodule.fragment.activity.VideoPreActivity;
import com.mediacloud.app.newsmodule.fragment.baoliao.OnItemClickListener;
import com.mediacloud.app.newsmodule.fragment.baoliao.TransUtils;
import com.mediacloud.app.newsmodule.fragment.baoliao.activity.BaoLiaoDetailActivity;
import com.mediacloud.app.newsmodule.fragment.baoliao.adapter.BaoLiaoDetailAdapter;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.detail.BaoLiaoDetailData;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.detail.BaoLiaoDetailModel;
import com.mediacloud.app.newsmodule.fragment.baoliao.model.detail.ImageGridItem;
import com.mediacloud.app.newsmodule.model.baoliao.list.list.TipVideoBean;
import com.mediacloud.app.newsmodule.newsdetail_component.NewsDetailComponentUtils;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.newsmodule.utils.ReadStatusInvoker;
import com.mediacloud.app.newsmodule.utils.ShareGridClickUtil;
import com.mediacloud.app.newsmodule.view.ShareComponent;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.share.model.ShareGridItem;
import com.mediacloud.app.user.controller.BaseController;
import com.mediacloud.app.user.model.UserInfo;
import com.mediacloud.app.user.utils.RxUtils;
import com.zly.widget.CollapsedTextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.functions.Consumer;

/**
 * Created by Yoake on 2018/8/28.
 */

public class BaoLiaoDetailFragment extends BaseFragment implements OnItemClickListener {
    private long id;
    private TextView mTitle;
    private TextView mNickName;
    private TextView mContent;
    private TextView mAddTime;
    private RecyclerView mRecyclerView;
    private BaoLiaoDetailAdapter adapter;
    //  private LinearLayout mLocationLayout;
    private TextView mLocation;
    //  private ImageView ImageLocation;
    /**
     * 阅读数
     */
    private TextView tvReads;
    private LinearLayout mReplyLayout;
    private TextView mReplyUser;
    protected CollapsedTextView mReply;
    private BaoLiaoMeta meta;
    // private View viewLine;
    BaoLiaoDetailActivity activity;
    int status;
    public Consumer<Pair<Integer, BaoLiaoMeta>> consumer;

    @Override
    public int getLayoutResID() {
        return R.layout.baoliao_detail_frag_layout;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        activity = (BaoLiaoDetailActivity) getActivity();
        id = getArguments().getLong("id");
        status = getArguments().getInt("status", 1);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
//        showActivityStateView(BaoLiaoDetailActivity.TYPE_LOADING);
        getDetail();
    }

    @Override
    public void initView() {
        initView(mRootView);
    }


    GridLayoutManager gridLayoutManager;

    public void initView(View view) {

//        appfac();
        //    viewLine = view.findViewById(R.id.viewLine);
        mTitle = view.findViewById(R.id.title);
        mNickName = view.findViewById(R.id.nickName);
        mContent = view.findViewById(R.id.content);
        mAddTime = view.findViewById(R.id.addTime);
        //  mLocationLayout = view.findViewById(R.id.locationLayout);
        tvReads = view.findViewById(R.id.tv_bao_liao_detail_reads);
        mLocation = view.findViewById(R.id.location);
        //    ImageLocation = view.findViewById(R.id.image_baoliao_location);
        mReplyLayout = view.findViewById(R.id.replyLayout);
        mReply = view.findViewById(R.id.mReplyText);
        mReplyUser = view.findViewById(R.id.replyUser);
        mRecyclerView = view.findViewById(R.id.mRecyclerView);
        View rootScroll = getView().findViewById(R.id.rootScroll);
        adapter = new BaoLiaoDetailAdapter(getActivity(), this, rootScroll);
        gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        mRecyclerView.setLayoutManager(gridLayoutManager);
        mRecyclerView.addItemDecoration(new XdNineGridDivider(getActivity().getResources().getDimensionPixelSize(R.dimen.dimen5)));
        mRecyclerView.setAdapter(adapter);
    }


    private void getDetail() {
        DataInvokeUtil.getZiMeiTiApi().getTipOffDetail(id + "").compose(TransUtils.fastJSonTransform(BaoLiaoDetailModel.class))
                .compose(RxUtils.<BaoLiaoDetailModel>schedulersTransformer())
                .subscribe(new BaseController().new BaseObserver<BaoLiaoDetailModel>() {
                    @Override
                    public void onNext(BaoLiaoDetailModel model) {
                        if (model.isState() && model.getData() != null && model.getData().getMeta() != null) {
                            setData(model.getData());
                            closeActivityshowStateView();
                        } else {
                            showActivityStateView(BaoLiaoDetailActivity.TYPE_NO_CONTENT);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        e.printStackTrace();
                        showActivityStateView(BaoLiaoDetailActivity.TYPE_NET_NOT_GIVE_FORCE);
                    }
                });
    }

    private void showActivityStateView(String type) {
        Activity activity = getActivity();
        if (activity instanceof BaoLiaoDetailActivity) {
            ((BaoLiaoDetailActivity) activity).showStateView(type, false);
        }
    }

    private void closeActivityshowStateView() {
        Activity activity = getActivity();
        if (activity instanceof BaoLiaoDetailActivity) {
            ((BaoLiaoDetailActivity) activity).closeStateView();
        }
    }

    private void setData(BaoLiaoDetailData data) {
        this.meta = data.getMeta();
        if (data.getMeta() != null) {
            articleItem.setTitle(data.getMeta().getTitle());
            articleItem.setSummary(data.getMeta().getContent());
            if (data.getMeta().getShortTitleStyle() != null && data.getMeta().getShortTitleStyle().size() > 0) {
                articleItem.setLogo(data.getMeta().getShortTitleStyle().get(0).getImgpath());
            }
            articleItem.setUrl(data.getMeta().getShareUrl());
        }
        status = data.getMeta().getStatus();
        if (consumer != null) {
            try {
                consumer.accept(Pair.create(status, data.getMeta()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String count = TextUtils.isEmpty(data.getMeta().getHitCount_format()) ? "0" : data.getMeta().getHitCount_format();
        tvReads.setText(StringUtils.toTenThousand(count) + "浏览");
        ((BaoLiaoDetailActivity) getActivity()).setArticleItem(data.getMeta());
        commentList(data, activity.getArticleItem());
        List<ImageGridItem> paths = new ArrayList<>();
//        if (data.getMeta().getTipoffinfoList() != null && data.getMeta().getTipoffinfoList().size() > 0) {
//
//            try {
//                JSONObject jsonObject = new JSONObject(GsonUtils.toJson(data.getMeta().getTipoffinfoList().get(0).getLiveAddress().get(0)));
//                String poster = jsonObject.optString("poster");
//                ImageGridItem item = new ImageGridItem(poster, true);
//                paths.add(item);
//
//
//            } catch (JSONException e) {
//                e.printStackTrace();
//            }
//
//        }

        if (data.getMeta().getShortTitleStyle() != null) {
            for (int i = 0; i < data.getMeta().getShortTitleStyle().size(); i++) {
                ImageGridItem item = new ImageGridItem(data.getMeta().getShortTitleStyle().get(i).getImgpath());
                item.setVideo(data.getMeta().getShortTitleStyle().get(i).getType().equals("video"));
                try {
                    if (data.getMeta().getTipoffinfoList() != null && data.getMeta().getTipoffinfoList().size() > 0) {
                        if (data.getMeta().getTipoffinfoList().get(0).getLiveAddress() != null && data.getMeta().getTipoffinfoList().get(0).getLiveAddress().size() > 0) {
                            TipVideoBean.LiveAddressBean liveAddressBean = data.getMeta().getTipoffinfoList().get(0).getLiveAddress().get(0);
                            item.setDuration(liveAddressBean.getFormats().get(0).getDuration());
                        }
                    }
                    paths.add(item);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }
        String catalog = data.getMeta().getCatalogName();
        String title = data.getMeta().getTitle();
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        spannableStringBuilder.append(catalog).append("\t\t\t").append(TextUtils.isEmpty(title) ? "" : title);
        // spannableStringBuilder.setSpan(new AbsoluteSizeSpan(getActivity().getResources().getDimensionPixelSize(R.dimen.dimen20), false), 0, catalog.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        //   spannableStringBuilder.setSpan(new StyleSpan(android.graphics.Typeface.BOLD), 0, catalog.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        Drawable drawable = getResources().getDrawable(R.drawable.vertical_line);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());


        spannableStringBuilder.setSpan(new ImageSpan(drawable), catalog.length() + 1, catalog.length() + 2, Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        mTitle.setText(spannableStringBuilder);

        mNickName.setText(data.getMeta().getNickName());
        mAddTime.setText(data.getMeta().getPublishTime());
        mContent.setText(data.getMeta().getContent());

        if (paths.size() == 1) {
            gridLayoutManager.setSpanCount(paths.size());
        } else if (paths.size() == 2 || paths.size() == 4) {
            gridLayoutManager.setSpanCount(2);
        } else {
            gridLayoutManager.setSpanCount(3);
        }
        adapter.setSpancount(gridLayoutManager.getSpanCount());

        adapter.setGridList(paths, meta);

//        adapter.setMeta(meta);

        if (paths.size() == 0) {
            mRecyclerView.setVisibility(View.GONE);
        }
        //    viewLine.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(data.getMeta().getLocation())) {
            mLocation.setText("所在位置:" + data.getMeta().getLocation());
            mLocation.setVisibility(View.VISIBLE);
            // ImageLocation.setVisibility(View.VISIBLE);
        } else {
            mLocation.setVisibility(View.GONE);
        }
        mReply.setTipsColor(DefaultBgUtil.getTintColor(requireContext()));
        if (!TextUtils.isEmpty(data.getMeta().getReplyContent())) {
            mReply.setText(data.getMeta().getReplyContent());
            if (TextUtils.isEmpty(data.getMeta().getReplySubject())) {
                mReplyUser.setText("回复:");
            } else {
                mReplyUser.setText(data.getMeta().getReplySubject());
            }
            mReplyLayout.setVisibility(View.VISIBLE);

        } else {
            mReplyLayout.setVisibility(View.GONE);
        }

        //爆料阅读数据采集
        UserInfo ui = UserInfo.getUserInfo(getContext());
//        String userId = ui == null?"":ui.getUserid();
//        String nickName = TextUtils.isEmpty(ui.getNickname())?ui.getUsername():ui.getNickname();
        AcquisitionManager.getInstance().click(ui, id + "", "", "",
                data.getMeta().getTitle(), data.getMeta().getContent());
//        OnairCollectUtil.read(getContext(),userId,"",
//                "",data.getMeta().getTitle(),data.getMeta().getContent(),nickName,"");
        addReads(data.getMeta());
    }

    private void addReads(BaoLiaoMeta meta) {
        ReadStatusInvoker readStatusInvoker = new ReadStatusInvoker(new DataInvokeCallBack<BaseMessageReciver>() {
            @Override
            public void success(BaseMessageReciver data) {
                Log.w(TAG, "readStatusInvoker  " + "success");
                if (data.state) {
                    try {
                        JSONObject dataObject = data.orginData.optJSONObject("data");
                        String reads = dataObject.optString("reads");
                        if (!TextUtils.isEmpty(reads)) {
                            tvReads.setText(StringUtils.toTenThousand(reads) + "浏览");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void fault(Object data) {
                Log.w(TAG, "readStatusInvoker  " + "fault");
            }
        });
        readStatusInvoker.readStatistics(meta.getId() + "", 1, 5);
    }

    @Override
    public void onClick(final int position) {
        if (adapter.getItem(position).isVideo()) {

            Intent intent = new Intent(getActivity(), VideoPreActivity.class);
            if (meta.getTipoffinfoList().size() > 0) {
                for (int i = 0; i < meta.getTipoffinfoList().get(0).getLiveAddress().size(); i++) {
                    if (meta.getTipoffinfoList().get(0).getLiveAddress().get(i).getFormats() != null && meta.getTipoffinfoList().get(0).getLiveAddress().get(i).getFormats().size() > 0) {
                        intent.putExtra("URL", meta.getTipoffinfoList().get(0).getLiveAddress().get(i).getFormats().get(0).getUrl());
                        break;
                    }
                }
            }
            startActivity(intent);
        } else {
            try {
                List<ImageGridItem> list = adapter.getData();
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < list.size(); i++) {
//                    if (!list.get(i).isVideo()) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("info", meta.getContent());
                    if (meta.getShortTitleStyle().get(i).getType().equals("image")) {
                        jsonObject.put("src", list.get(i).getPath());
                    } else {
                        if (meta.getTipoffinfoList() != null && meta.getTipoffinfoList().size() > 0) {
                            if (meta.getTipoffinfoList().get(0).getLiveAddress() != null && meta.getTipoffinfoList().get(0).getLiveAddress().size() > 0) {
                                if (meta.getTipoffinfoList().get(0).getLiveAddress().get(0).getFormats() != null && meta.getTipoffinfoList().get(0).getLiveAddress().get(0).getFormats().size() > 0) {
                                    if (meta.getShortTitleStyle() != null && meta.getShortTitleStyle().size() > 0) {
                                        if (!TextUtils.isEmpty(meta.getShortTitleStyle().get(0).getImgpath())) {
                                            jsonObject.put("src", meta.getTipoffinfoList().get(0).getLiveAddress().get(0).getFormats().get(0).getImage());
                                        }
                                    }
                                }
                            }
                        }
                    }
                    jsonArray.put(jsonObject);
//                    }
                }
                final ArticleItem imgArticle = new ArticleItem();
                imgArticle.setTitle(meta.getCatalogName());

                imgArticle.setImage(jsonArray.toString());
                imgArticle.setType(TypeX.NEWS.PHOTOS);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (getActivity() != null)
                            NewsItemClickUtils.OpenItemNewsHandle(getActivity(), TypeX.NEWS.PHOTOS, imgArticle, new CatalogItem(), position, true);
                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }


        }
    }


    private void commentList(BaoLiaoDetailData data, ArticleItem articleItem) {

        ArrayList<ComponentItem> components = new ArrayList<>();
        if (data.getComponents() != null && data.getComponents().size() > 0) {
            try {
                for (int i = 0; i < data.getComponents().size(); i++) {

                    JSONObject componentObj = new JSONObject(GsonUtils.toJson(data.getComponents().get(i)));
                    ComponentItem component = new ComponentItem();
                    component.parse(componentObj);
                    components.add(component);
                }


            } catch (Exception e) {

            }

        }
        View rootScroll = getView().findViewById(R.id.rootScroll);
        NewsDetailComponentUtils.addComponentList(findViewById(R.id.contentView), components, articleItem, getActivity(), getChildFragmentManager(), 5, this, data.getMeta().getCatalogId(), rootScroll);
    }


    ArticleItem articleItem = new ArticleItem();

    @ShareComponent.AdapterViewItemClicked
    public void onItemClick(AdapterView<?> parent, View view, int position, long id, ShareGridItem item) {
        Log.i(TAG, "@ShareComponent.AdapterViewItemClicked onItemClick" + parent + "view " + view + "position " + position + "id " + id);

        ShareGridClickUtil.ShareGridClickHandle(item.label, articleItem, new CatalogItem(), getActivity());
    }


    @Override
    public void onDestroyView() {
        if (adapter != null) {
            adapter.destroy();
        }
        super.onDestroyView();
    }
}